﻿using Basic.FormCollect;
using Basic.FormRemoteModel;
using Basic.FormRemoteModel.QueryInter.Model;
using Basic.FormRemoteModel.TableRecord.Model;
using Basic.UserFormService.Interface;
using Basic.UserFormService.Model.PhyForm;
using WeDonekRpc.Helper;

namespace Basic.UserFormService.Extend
{
    internal class FormTableAddRowService : IFormTableAddRowService
    {
        private readonly ICustomFormCollect _Form;
        private readonly IFormRecordService _Record;
        private readonly IPhysicsAddRowService _Physics;
        private readonly IPhyFormRowService _PhyForm;
        public FormTableAddRowService ( IFormRecordService record,
            IPhysicsAddRowService physics,
            IPhyFormRowService phyForm,
            ICustomFormCollect form )
        {
            this._PhyForm = phyForm;
            this._Form = form;
            this._Record = record;
            this._Physics = physics;
        }
        public bool AddRow ( TableDataRow row )
        {
            Dictionary<long, FormVal> vals = this._Record.GetVals(new FormGetVals
            {
                LinkPK = row.LinkPK,
                LinkType = row.LinkType,
                Cols = row.Relation.ConvertAll(a => new FormCol
                {
                    ColId = a.ColId,
                    FormId = a.FormId,
                    Keywords = a.Keywords,
                })
            });
            if ( vals.Count == 0 )
            {
                return false;
            }
            PhyFormBase form = this._Form.Get<PhyFormBase>(row.ToFormId, a => new PhyFormBase
            {
                Id = a.Id,
                FormType = a.FormType,
                PhyGroupId = a.PhyGroupId,
                PhyTableName = a.TableName
            });
            if ( form.FormType == FormType.物理表单 )
            {
                return this._Physics.AddRow(vals, row);
            }
            else if ( form.FormType == FormType.代理表单 )
            {
                return this._PhyForm.AddRow(vals, form, row);
            }
            else
            {
                throw new ErrorException("form.type.error");
            }
        }
    }
}